﻿var oWCTeams = {};
var oWCTeamsSorted = {};


var oWCTeamNews = {};
var oWCTeamNewsWidget = {};
var oWCMatches = {};

var oWCStages = {};
var oWCStagesMap = {};

var oWCGroups = {};
var oWCGroupsMap = {};

var oWCLiveMatch = {};

var oWCSelectedMatches = {};
var oWCLiveMatches = {};

var bMatchesLoaded = false;
var bRefreshMyTeam = false;


var currentNew = 0;
var tabId;

var currentStage = 0;
var liveMatch = "";




function setTabFocus(){
    trackEvent("TAB", tabId);
    chrome.tabs.update(tabId, {
        selected: true
    }, null);
}


function createTab(){
    chrome.tabs.create({
        url: "view/options.html"
    });
}


function showConfig(){
    chrome.tabs.getAllInWindow(null, function(tabs){
        var bReturn = false;
        var strOptionsPage = "chrome-extension://" + chrome.i18n.getMessage("@@extension_id") + "/view/options.html";
        tabs.forEach(function(tab){
            if (tab.url == strOptionsPage) {
                tabId = tab.id;
                bReturn = true;
            }
        });
        if (!bReturn) {
            createTab();
        }
        else {
            setTabFocus();
        }
    });
}

function getMyTeamName(){
    if (localStorage['my_team'].split("|")[2] == '---') 
        return getUI("config_txt_all_teams");
    else 
        return localStorage['my_team'].split("|")[2].toUpperCase();
}

function getMyTeamGroupName(){
    if (!localStorage['my_team_group_name']) 
        return "";
    else 
        return "(" + localStorage['my_team_group_name'] + ")";
}


function init(){
    // reset icon alert
    chrome.extension.getBackgroundPage().resetIconAlert();
    
    // get selected Matches
    !localStorage.getObject('wcSelectedMatches') ? oWCSelectedMatches = {} : oWCSelectedMatches = localStorage.getObject('wcSelectedMatches');
    
    !localStorage.getObject('wcSelectedLiveMatches') ? oWCSelectedLiveMatches = {} : oWCSelectedLiveMatches = localStorage.getObject('wcSelectedLiveMatches');
    
    $('#tabs').tabs({
        select: function(event, ui){
            // My team
            if (ui.index == 0) {
                if (bRefreshMyTeam) {
                    $("#popup_txt_myteam").text(getMyTeamName());
                    $("#my-team-div").click(onMyTeamClick);
                    $("#popup_txt_myteam_group").text(getMyTeamGroupName());
                    $("#div_popup_latest_news > div.noticia").remove();
                    $("#popup_txt_load_more_news").remove();
                    $("#div_popup_next_match > div.middle").remove();
                    $("#div_popup_last_match > div.middle").remove();
                    $("#popup_img_loading_latest_news").fadeIn();
                    $("#popup_img_loading_next_match").fadeIn();
                    $("#popup_img_loading_last_match").fadeIn();
                    setTimeout("getTeamConfig();", 100);
                    setTimeout("getTeamNews()", 500);
                    setTimeout("getMyTeamNextLastMatches()", 500);
                    
                    chrome.browserAction.setBadgeText({
                        text: ""
                    });
                    $("#config-container").hide();
                    $("#main-container").show();
                    bRefreshMyTeam = false;
                }
            }
            
            // Live
            if (ui.index == 1) {
                setTimeout("getLive();", 500);
            }
            
            
            // Matches
            if (ui.index == 2) {
                if (!bMatchesLoaded) {
                    setTimeout("getMatches();", 500);
                    bMatchesLoaded = true;
                }
                else {
                    // refresh selected teams
                    $('.partido > :checkbox').each(function(index){
                        if (oWCSelectedMatches[$(this).attr("id").split("chk").join("")] != undefined) 
                            $(this).attr("checked", true);
                        else 
                            $(this).attr("checked", false);
                    });
                }
            }
            
        }
    });
    
    translateUI();
    
    $("#cmb_my_team").change(onMyTeamChanged);
    $("#chk_follow_my_team").change(onChkFollowMyTeamChanged);
    $("#chk_follow_my_group_teams").change(onChkFollowMyGroupTeamsChanged);
    $("#chk_follow_all_teams").change(onChkFollowAllTeamsChanged);
    
    
    if (isFirstTime()) {
        chrome.browserAction.setBadgeText({
            text: "?"
        });
        
        chrome.tabs.getAllInWindow(null, function(tabs){
            var bReturn = false;
            var strOptionsPage = "chrome-extension://" + chrome.i18n.getMessage("@@extension_id") + "/view/options.html";
            tabs.forEach(function(tab){
                if (tab.url == strOptionsPage) {
                    tabId = tab.id;
                    bReturn = true;
                }
            });
            if (!bReturn) {
                setTimeout("createTab()", 2000);
            }
            else {
                setTimeout("setTabFocus()", 2000);
            }
        });
        
        $("#main-container").hide();
        $("#config-container").show();
    }
    else {
        var follow_my_team = localStorage['follow_my_team'];
        if (!follow_my_team) {
            localStorage.setObject('follow_my_team', 1);
            follow_my_team = 1;
        }
        
        var follow_my_group_teams = localStorage['follow_my_group_teams'];
        if (!follow_my_group_teams) {
            localStorage.setObject('follow_my_group_teams', 1);
            follow_my_group_teams = 1;
        }
        
        
        var follow_all_teams = localStorage['follow_all_teams'];
        if (!follow_all_teams) {
            localStorage.setObject('follow_all_teams', 1);
            follow_all_teams = 1;
        }
        
        
        if (follow_my_team == 1) {
            $("#chk_follow_my_team").attr("checked", true);
        }
        
        if (follow_my_group_teams == 1) {
            $("#chk_follow_my_group_teams").attr("checked", true);
        }
        
        if (follow_all_teams == 1) 
            $("#chk_follow_all_teams").attr("checked", true);
        
        
        setTimeout("getTeamConfig();", 100);
        setTimeout("getTeamNews()", 500);
        setTimeout("getMyTeamNextLastMatches()", 500);
        
        chrome.browserAction.setBadgeText({
            text: ""
        });
        $("#config-container").hide();
        $("#main-container").show();
    }
}

function translateUI(){
    $("span").each(function(index, item){
        setTextUI(item.id);
    })
    $("#popup_txt_myteam").text(getMyTeamName());
    $("#my-team-div").click(onMyTeamClick);
    $("#popup_txt_myteam_group").text(getMyTeamGroupName());
    
    $("#popup_btn_save").attr("value", getUI("popup_txt_save"));
    
    if (localStorage['my_team'] == "---|---|---") {
        $("#team_flag").hide();
        $("#team_flag_config").hide();
    }
    else {
        $("#team_flag").attr("src", String.format(flag_pattern_m, localStorage['my_team'].split("|")[1]));
        $("#team_flag_config").attr("src", String.format(flag_pattern_s, localStorage['my_team'].split("|")[1]));
        $("#team_flag").show();
        $("#team_flag_config").show();
    }
}


function getTeamNews(){
    var strTeamUrl = "";
    
    if (localStorage['my_team'].split("|")[0] == "---") 
        strTeamUrl = String.format(getUI('main_url_feed_2') + feed_news_fifa, localStorage['my_team'].split("|")[0]);
    else 
        strTeamUrl = String.format(getUI('main_url_feed_2') + feed_news, localStorage['my_team'].split("|")[0]);
    
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            
            var strNewsPattern = "<div id='{0}' style='display:none' class='noticia'><a href='{2}?" + url_suffix + "' id='{0}_anchor' target='_blank'><span>{4}</span> - {3}</a><img src='{1}'/>{5}</div>";
            var json = "";
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            
            json = $.xml2json(xmlString);
            
            
            if (json != "") {
                oWCTeamNews = json;
                var strNew = "";
                for (var i = 0; i < oWCTeamNews.channel.item.length; i++) {
                    if (localStorage['my_team'].split("|")[0] == "---") 
                        strNew = String.format(strNewsPattern, getID(oWCTeamNews.channel.item[i].link), oWCTeamNews.channel.item[i].enclosure.url.split("%5fsmall").join("%5fthumb"), oWCTeamNews.channel.item[i].link, oWCTeamNews.channel.item[i].title, getLocalDate(oWCTeamNews.channel.item[i].pubDate), oWCTeamNews.channel.item[i].description);
                    else 
                        strNew = String.format(strNewsPattern, getID(oWCTeamNews.channel.item[i].link), oWCTeamNews.channel.item[i].enclosure.url.split("%5fsmall").join("%5fthumb"), getUI("main_url") + "/worldcup" + oWCTeamNews.channel.item[i].link.split(".xml").join(".html"), oWCTeamNews.channel.item[i].title, getLocalDate(oWCTeamNews.channel.item[i].pubDate), oWCTeamNews.channel.item[i].description);
                    $("#div_popup_latest_news").append(strNew);
                }
            }
            
            
            $('<div class="bottom"><a href="#" onclick="javascript:onLoadMoreNewsClick()" id="popup_txt_load_more_news">' + getUI("popup_txt_load_more_news") + '</a></div>').insertAfter($('#div_popup_latest_news'));
            
            //$("#popup_txt_load_more_news").click(onLoadMoreNewsClick);
            
            $("#popup_img_loading_latest_news").hide();
            $("#" + getID(oWCTeamNews.channel.item[0].link)).fadeIn('slow');//show();
            currentNew = 0;
        }
    }
    xhr.send();
}


function getMyTeamNextLastMatches(){
    var bFoundNextMatch = false;
    var bFoundLastMatch = false;
    
    var strIdMyTeam = localStorage['my_team'].split("|")[1];
    
    var strTeamUrl = "";
    
    if (!bWCDebug) 
        strTeamUrl = getUI('main_url_feed_2') + feed_matches;
    else 
        strTeamUrl = feed_matches_debug;
    
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            "<div class='middle'><strong><img src='{0}'/>&nbsp;{1} {2} {3}&nbsp;<img src='{4}'/></strong><span>{5}</span>{6}</div>";
            var strMatchPatternToBePlayed = "<div id='match{0}' class='middle'><strong><input style='float: left; margin: 4px 5px 0 0;' type='checkbox' title='" + getUI("popup_txt_follow_this_match") + "' id='chk{0}' group='{8}' team_a='{9}' team_b='{10}' teams='{11}'/><div class='equipos' onclick='showMatch(\"{7}\");'><img src='{1}'/>&nbsp;{2} vs {3} <img src='{4}'/></strong></div><p onclick='showMatch(\"{7}\");'><span>{5}</span>&nbsp;{6}</div>";
            var strMatchPattern = "<div id='match{0}' class='middle'><strong><div class='equipos' onclick='showMatch(\"{7}\");'><img src='{1}'/>&nbsp;{2} {8}:{9} {3} <img src='{4}'/></strong></div><p onclick='showMatch(\"{7}\");'><span>{5}</span>&nbsp;{6}</div>";
            var json = "";
            var selectedTab = "";
            
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            
            json = $.xml2json(xmlString);
            
            
            if (json != "") {
                oWCMatches = json;
                var strNew = "";
                oWCStages = new Array();
                oWCGroups = new Array();
                var j = 0;
                var k = 0;
                var strIdTab = "";
                var strIdStage = "";
                var strIdGroup = "";
                
                for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                    // to be played 
                    if ((oWCMatches.Data.Match[i].Status.code == "1") && (!bFoundNextMatch)) {
                        if ((oWCMatches.Data.Match[i].Team[0].ShortName == strIdMyTeam) || (oWCMatches.Data.Match[i].Team[1].ShortName == strIdMyTeam)) {
                            $("#div_popup_next_match").append(String.format(strMatchPatternToBePlayed, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].FullName, oWCMatches.Data.Match[i].Team[1].FullName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), oWCMatches.Data.Match[i].Group.code, oWCMatches.Data.Match[i].Team[0].code, oWCMatches.Data.Match[i].Team[1].code, oWCMatches.Data.Match[i].ShortName));
                            bFoundNextMatch = true;
                        }
                        else {
                            if (strIdMyTeam == "---") {
                                $("#div_popup_next_match").append(String.format(strMatchPatternToBePlayed, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].FullName, oWCMatches.Data.Match[i].Team[1].FullName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), oWCMatches.Data.Match[i].Group.code, oWCMatches.Data.Match[i].Team[0].code, oWCMatches.Data.Match[i].Team[1].code, oWCMatches.Data.Match[i].ShortName));
                                bFoundNextMatch = true;
                            }
                        }
                    }
                }
                
                for (var i = oWCMatches.Data.Match.length - 1; i >= 0; i--) {
                    if ((oWCMatches.Data.Match[i].Status.code == "0") && (!bFoundLastMatch)) {
                        if ((oWCMatches.Data.Match[i].Team[0].ShortName == strIdMyTeam) || (oWCMatches.Data.Match[i].Team[1].ShortName == strIdMyTeam)) {
                            $("#div_popup_last_match").append(String.format(strMatchPattern, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].FullName, oWCMatches.Data.Match[i].Team[1].FullName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), oWCMatches.Data.Match[i].Result.Live.H, oWCMatches.Data.Match[i].Result.Live.A));
                            bFoundLastMatch = true;
                        }
                        else {
                            if (strIdMyTeam == "---") {
                                $("#div_popup_last_match").append(String.format(strMatchPattern, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].FullName, oWCMatches.Data.Match[i].Team[1].FullName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), oWCMatches.Data.Match[i].Result.Live.H, oWCMatches.Data.Match[i].Result.Live.A));
                                bFoundLastMatch = true;
                            }
                        }
                    }
                }
                
                $('.middle > strong > :checkbox').each(function(index){
                    if (oWCSelectedMatches[$(this).attr("id").split("chk").join("")] != undefined) 
                        $(this).attr("checked", true);
                    else 
                        $(this).attr("checked", false);
                });
                
                $('.middle > strong > :checkbox').click(onChkMatchClick);
                
                $("#popup_img_loading_next_match").fadeOut();
                $("#popup_img_loading_last_match").fadeOut();
                $(".match").fadeIn('slow');
                
            }
        }
    }
    xhr.send();
}

function getMatches(){
    // get selected Matches
    !localStorage.getObject('wcSelectedMatches') ? oWCSelectedMatches = {} : oWCSelectedMatches = localStorage.getObject('wcSelectedMatches');
    
    $("#div_popup_stages > .stage").remove();
    
    var strTeamUrl = "";
    
    if (!bWCDebug) 
        strTeamUrl = getUI('main_url_feed_2') + feed_matches;
    else 
        strTeamUrl = feed_matches_debug;
    
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            var strStagePattern = "<div id='stage{0}' class='stage'><!--{1}--><div id='tab{0}'><div></div><div><ul class='lista-grupos'></ul></div></div><div class='bottom' ><div style='display:none'><span id='popup_txt_select' class='link_text'></span>:&nbsp;<a href='javascript:onSelectAllClick(\"stage{0}\");'><span id='popup_txt_select_all' class='link'></span></a>,&nbsp;<a href='javascript:onSelectNoneClick(\"stage{0}\");'><span id='popup_txt_select_none' class='link'></span></a></div></div></div>";
            var strGroupPattern = "<div id='group{0}' class='fase-previa'></div>";
            var strMatchPatternToBePlayed = "<div id='match{0}' class='partido'><input type='checkbox' title='" + getUI("popup_txt_follow_this_match") + "' id='chk{0}' group='{8}' team_a='{9}' team_b='{10}' teams='{11}'/><div class='equipos' onclick='showMatch(\"{7}\");'><span class='equipo1'><img src='{1}'/>&nbsp;{2}</span> vs <span class='equipo2'>{3} <img src='{4}'/></span></div><p onclick='showMatch(\"{7}\");'><strong>{5}</strong>{6}</div>";
            var strMatchPattern = "<div id='match{0}' class='partido' onclick='showMatch(\"{9}\");'>																					   <div class='equipos'><span class='equipo1'><img src='{1}'/>&nbsp;{2}</span>{7} : {8}	<span class='equipo2'>{3} <img src='{4}'/></span></div><p><strong>{5}</strong>{6}</div>";
            var json = "";
            var selectedTab = "";
            
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            
            json = $.xml2json(xmlString);
            
            
            if (json != "") {
                oWCMatches = json;
                var strNew = "";
                oWCStages = new Array();
                oWCGroups = new Array();
                var j = 0;
                var k = 0;
                var strIdTab = "";
                var strIdStage = "";
                var strIdGroup = "";
                for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                    strIdStage = "#stage" + oWCMatches.Data.Match[i].Round.code;
                    var oDivStage = $(strIdStage);
                    if (oDivStage.length == 0) {
                        $("#cmb_popup_stage_navigation").append("<option value='" + j + "'>" + oWCMatches.Data.Match[i].Round.text + "</option>");
                        
                        j++;
                        $("#div_popup_stages").append(String.format(strStagePattern, oWCMatches.Data.Match[i].Round.code, oWCMatches.Data.Match[i].Round.text));
                        if (j > 1) {
                            $(strIdStage).attr("style", "display:none");
                        }
                        strIdTab = '#tab' + oWCMatches.Data.Match[i].Round.code;
                        $(strIdTab).tabs();
                    }
                    
                    if (oWCMatches.Data.Match[i].Group.code.length > 0) {
                        strIdGroup = "#group" + oWCMatches.Data.Match[i].Group.code;
                        var oTabGroup = $(strIdGroup);
                        
                        if (oTabGroup.length == 0) {
                            $(strIdTab).append(String.format(strGroupPattern, oWCMatches.Data.Match[i].Group.code));
                            $(strIdTab).tabs("add", strIdGroup, getGroupShortName(oWCMatches.Data.Match[i].Group.text));
                            $(strIdTab + " > ul").attr("style", "font-size:0.8em");
                        }
                        // to be played or playing
                        if (oWCMatches.Data.Match[i].Status.code == "1" || oWCMatches.Data.Match[i].Status.code == "3") {
                            $(strIdGroup).append(String.format(strMatchPatternToBePlayed, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].ShortName, oWCMatches.Data.Match[i].Team[1].ShortName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), oWCMatches.Data.Match[i].Group.code, oWCMatches.Data.Match[i].Team[0].code, oWCMatches.Data.Match[i].Team[1].code, oWCMatches.Data.Match[i].ShortName));
                        }
                        else {
                            $(strIdGroup).append(String.format(strMatchPattern, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].ShortName, oWCMatches.Data.Match[i].Team[1].ShortName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', oWCMatches.Data.Match[i].Result.Live.H, oWCMatches.Data.Match[i].Result.Live.A, addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink)));
                        }
                        
                        if ((localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[0].ShortName) || (localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[1].ShortName)) {
                            setTimeout("selectTabs('" + strIdTab + "','" + strIdGroup + "');", 100);
                        }
                    }
                    else {
                    
                        strIdGroup = strIdTab + "_group";
                        var oDivGroup = $(strIdGroup);
                        if (oDivGroup.length == 0) {
                            $(strIdTab).append("<div id='" + strIdGroup.split("#").join("") + "' class='fase-previa'></div>")
                        }
                        // No hay grupos
                        if (oWCMatches.Data.Match[i].Status.code == "1") 
                            $(strIdGroup).append(String.format(strMatchPatternToBePlayed, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].ShortName, oWCMatches.Data.Match[i].Team[1].ShortName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), '', oWCMatches.Data.Match[i].Team[0].code, oWCMatches.Data.Match[i].Team[1].code, oWCMatches.Data.Match[i].ShortName));
                        else 
                            $(strIdGroup).append(String.format(strMatchPattern, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].ShortName, oWCMatches.Data.Match[i].Team[1].ShortName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', oWCMatches.Data.Match[i].Result.Live.H, oWCMatches.Data.Match[i].Result.Live.A, addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink)));
                        
                    }
                }
                
                
                $("#popup_txt_select").text(getUI("popup_txt_select"));
                $("#popup_txt_select_all").text(getUI("popup_txt_select_all"));
                $("#popup_txt_select_none").text(getUI("popup_txt_select_none"));
                
                $('.partido > :checkbox').each(function(index){
                    if (oWCSelectedMatches[$(this).attr("id").split("chk").join("")] != undefined) 
                        $(this).attr("checked", true);
                    else 
                        $(this).attr("checked", false);
                });
                
                $('.partido > :checkbox').click(onChkMatchClick);
                
                $("#popup_img_loading_stages").fadeOut();
                $("#popup_img_matches").fadeIn();
                
                $("#cmb_popup_stage_navigation").change(onCmbStageNavigationChange);
                $("#cmb_popup_stage_navigation").show();
                
                // show current stage
                var dateStage2 = new Date();
                var dateStage3 = new Date();
                var dateStage4 = new Date();
                var dateStage5 = new Date();
                var dateStage6 = new Date();
                var dateToday = new Date();
                dateStage2.setFullYear(2010, 5, 26);
                dateStage3.setFullYear(2010, 5, 30);
                dateStage4.setFullYear(2010, 6, 4);
                dateStage5.setFullYear(2010, 6, 8);
                dateStage6.setFullYear(2010, 6, 11);
                
                if (dateToday < dateStage2) {
                    // do nothing
                }
                else {
                    if ((dateToday >= dateStage2) && (dateToday < dateStage3)) {
                        // Stage-2
                        $("#cmb_popup_stage_navigation").val(1);
                        onCmbStageNavigationChange();
                    }
                    else {
                        if ((dateToday >= dateStage3) && (dateToday < dateStage4)) {
                            // Stage-3
                            $("#cmb_popup_stage_navigation").val(2);
                            onCmbStageNavigationChange();
                        }
                        else {
                            if ((dateToday >= dateStage4) && (dateToday < dateStage5)) {
                                // Stage-4
                                $("#cmb_popup_stage_navigation").val(3);
                                onCmbStageNavigationChange();
                            }
                            else {
                                if ((dateToday >= dateStage5) && (dateToday < dateStage6)) {
                                    // Stage-5
                                    $("#cmb_popup_stage_navigation").val(4);
                                    onCmbStageNavigationChange();
                                }
                                else {
                                    // Stage-6
                                    $("#cmb_popup_stage_navigation").val(5);
                                    onCmbStageNavigationChange();
                                }
                            }
                        }
                    }
                }
                
            }
        }
    }
    xhr.send();
}


function getCountry(strCountry){
    if (oWCTeams[strCountry] != undefined) 
        return oWCTeams[strCountry].FullName;
    else 
        return strCountry;
}


function getLive(){
    // reset fields
    $("#div_live_matches").tabs("destroy");
    $("#div_live_matches").empty();
    $("#div_next_match").remove();
    $("#div_live_matches").append("<ul></ul>");
    $("#popup_img_loading_live").fadeIn();
    
    // get selected Matches
    !localStorage.getObject('wcSelectedMatches') ? oWCSelectedMatches = {} : oWCSelectedMatches = localStorage.getObject('wcSelectedMatches');
    
    
    var strMatchPattern = "<div id='match{0}' class='partido' onclick='showMatch(\"{9}\");'><span class='equipo1'><img src='{1}'/>&nbsp;{2}</span><span class='resultado'>{7} : {8}</span><span class='equipo2'>{3} <img src='{4}'/></span>  <span class='info-partido'>{5}<br>{6}</span></div>";
    var strMatchSimplePattern = "<span class='equipo1'><img src='{0}'/>&nbsp;{1}</span>&nbsp;vs&nbsp;<span class='equipo2'>{2} <img src='{3}'/></span>";
    var strMatchPatternToBePlayed = "<div id='div_next_match' style='display:none' class='no-match'><div class='next'>" + getUI("popup_txt_next_match").toUpperCase() + ":</div><div id='match{0}' class='equipos'  onclick='showMatch(\"{10}\");'><span class='equipo1'><img src='{1}'/>{2}</span> vs <span class='equipo2'>{3} <img src='{4}'/></span></div><p><input type='checkbox' title='" + getUI("popup_txt_follow_this_match") + "' id='chk{0}' group='{7}' team_a='{8}' team_b='{9}' teams='{11}'/>&nbsp;<strong>{5}</strong><br/>{6}</p></div>";
    
    var strTeamUrl = "";
    var strIdTab = "";
    var bShowLiveMatch = false;
    
    var bIsNextMatchLoaded = false;
    var bIsLiveMatchLoaded = false;
    
    if (!bWCDebug) 
        strTeamUrl = getUI('main_url_feed_2') + feed_matches;
    else 
        strTeamUrl = feed_matches_debug;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            var json = "";
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            
            json = $.xml2json(xmlString);
            
            
            if (json != "") {
                oWCMatches = json;
                
                // sort by UTCDateTime							
                oWCMatches.Data.Match.sort(sort_by('MatchNumber', false, parseInt));
                var bShowNextMatch = true;
                for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                    bShowLiveMatch = false;
                    if (localStorage['follow_my_team'] == 1) 
                        if ((localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[0].ShortName) || (localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[1].ShortName)) {
                            bShowLiveMatch = true;
                        }
                    
                    if (oWCSelectedMatches != undefined) 
                        if (oWCSelectedMatches[oWCMatches.Data.Match[i].code] != undefined) 
                            bShowLiveMatch = true;
                    
                    if (bShowLiveMatch) {
                        switch (oWCMatches.Data.Match[i].Status.code) {
                            // to be played
                            case "1":
                                if (bShowNextMatch) {
                                    var strHeadText = "";
                                    strHeadText = String.format(strMatchPatternToBePlayed, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].FullName.toUpperCase(), oWCMatches.Data.Match[i].Team[1].FullName.toUpperCase(), String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', oWCMatches.Data.Match[i].Group.code, oWCMatches.Data.Match[i].Team[0].code, oWCMatches.Data.Match[i].Team[1].code, addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink), oWCMatches.Data.Match[i].ShortName);
                                    $("#div_popup_live").append(strHeadText);
                                    if (oWCSelectedMatches[oWCMatches.Data.Match[i].code] != undefined) {
                                        $("#chk" + oWCMatches.Data.Match[i].code).attr("checked", true);
                                    }
                                    else 
                                        $("#chk" + oWCMatches.Data.Match[i].code).attr("checked", false);
                                    bShowNextMatch = false;
                                    bIsNextMatchLoaded = true;
                                }
                                break;
                                
                            // live mode
                            case "3":
                                $("#div_live_matches").tabs();
                                var strHeadText = "";
                                var strIdMatchLive = "";
                                strIdMatchLive = "#liveMatch" + oWCMatches.Data.Match[i].code;
                                
                                strHeadText = String.format(strMatchSimplePattern, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].ShortName, oWCMatches.Data.Match[i].Team[1].ShortName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName));
                                
                                $("#div_live_matches").tabs("add", strIdMatchLive, strHeadText);
                                $(strIdMatchLive).append("<div>" + String.format(strMatchPattern, oWCMatches.Data.Match[i].code, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].FullName.toUpperCase(), oWCMatches.Data.Match[i].Team[1].FullName.toUpperCase(), String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), getLocalDate(oWCMatches.Data.Match[i].UTCDateTime), oWCMatches.Data.Match[i].Venue.Stadium.text + ' (' + oWCMatches.Data.Match[i].Venue.Name + ')', oWCMatches.Data.Match[i].Result.Live.H, oWCMatches.Data.Match[i].Result.Live.A, addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink)) + "</div><div class='match_live'><table style='display:none' id='live" + oWCMatches.Data.Match[i].code + "'  border='0' cellspacing='0' cellpadding='2' width='100%'></table></div><div class='mas-info'>" + getUI("popup_more_info_follow") + "</div>");
                                
                                setTimeout("showLiveMatch('" + oWCMatches.Data.Match[i].code + "','" + addUrlSuffix(oWCMatches.Data.Match[i].OfficialSiteLink) + "');", 100);
                                bIsLiveMatchLoaded = true;
                                break;
                        }
                    }
                }
                
                $('.no-match :checkbox').each(function(index){
                    if (oWCSelectedMatches[$(this).attr("id").split("chk").join("")] != undefined) 
                        $(this).attr("checked", true);
                    else 
                        $(this).attr("checked", false);
                });
                
                $('.no-match :checkbox').click(onChkMatchClick);
                
                $('.match_stage > :checkbox').each(function(index){
                    if (oWCSelectedMatches[$(this).attr("id").split("chk").join("")] != undefined) 
                        $(this).attr("checked", true);
                    else 
                        $(this).attr("checked", false);
                    
                });
                
                if (bIsNextMatchLoaded && !bIsLiveMatchLoaded) 
                    $("#div_next_match").show();
                
                $('.match_stage > :checkbox').click(onChkMatchClick);
                
                $("#popup_img_loading_live").fadeOut();
                
            }
        }
    }
    xhr.send();
}

function showLiveMatch(strMatchCode, strMatchLink){
    var strTeamUrl = "";
    
    if (!bWCDebug) 
        strTeamUrl = getUI('main_url_feed_2') + String.format(feed_live_match, strMatchCode);
    else 
        strTeamUrl = String.format(feed_live_match_debug, strMatchCode);
    
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            
            var strLivePattern = "<tr class='{0}'><td>{1}</td><td>{2} {3}</td><!--<td>{3}</td><td>{4}</td>--><td><a href='#' onclick='shareFacebook(\"{6}\",\"{5}\");'><img src='../img/ico-facebook.gif' alt='' /></a></td><td><a href='#' onclick='shareTwitter(\"{6}\",\"{5}\");'><img src='../img/ico-twitter.gif' alt=''></a></td><td><a href='#' onclick='shareBuzz(\"{6}\",\"{5}\");'><img src='../img/ico-googlewave.gif' alt=''></a></td></tr>";
            var strLivePatternNoShare = "<tr class='{0} destaca' ><td>{1}</td><td >{4} ({2}) {3}</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>";
            var json = "";
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            json = $.xml2json(xmlString);
            if (json != "") {
                oWCLiveMatch = json;
                
                if (oWCLiveMatch.Data.Match.Actions.Action.length == undefined) {
                    if (oWCLiveMatch.Data.Match.Actions.Action.Kind.code in match_live_events) {
                        var strTime = "";
                        var strPlayer = "";
                        var strTeam = "";
                        oWCLiveMatch.Data.Match.Actions.Action.Time.text == undefined ? strTime = "" : strTime = oWCLiveMatch.Data.Match.Actions.Action.Time.text;
                        oWCLiveMatch.Data.Match.Actions.Action.Player.text == undefined ? strPlayer = "" : strPlayer = oWCLiveMatch.Data.Match.Actions.Action.Player.text;
                        oWCLiveMatch.Data.Match.Actions.Action.Team.text == undefined ? strTeam = "" : strTeam = oWCLiveMatch.Data.Match.Actions.Action.Team.text;
                        var strShareText = "";
                        //strShareText = strTime + " " + oWCLiveMatch.Data.Match.Actions.Action.Kind.text + " " + strPlayer + " (" + oWCLiveMatch.Data.Match.Actions.Action.Period.text + ")";
                        
                        strShareText = "[#" + oWCLiveMatch.Data.Match.Team[0].ShortName + " " + oWCLiveMatch.Data.Match.Result.Live.H + ":" + oWCLiveMatch.Data.Match.Result.Live.A + " #" + oWCLiveMatch.Data.Match.Team[1].ShortName + "] " + strTime + " " + oWCLiveMatch.Data.Match.Actions.Action.Kind.text + " " + strPlayer + " (" + oWCLiveMatch.Data.Match.Actions.Action.Period.text + ")";
                        strShareText = strShareText.split("'").join("&#039;");
                        strShareText = URLEncode(strShareText);
                        if (oWCLiveMatch.Data.Match.Actions.Action.Kind.code in match_live_share_events) {
                            $("#live" + oWCLiveMatch.Data.Match.code).prepend(String.format(strLivePattern, oWCLiveMatch.Data.Match.Actions.Action.Kind.code, strTime, oWCLiveMatch.Data.Match.Actions.Action.Kind.text, strTeam, oWCLiveMatch.Data.Match.Actions.Action.Period.text, strShareText, strMatchLink));
                        }
                        else {
                            $("#live" + oWCLiveMatch.Data.Match.code).prepend(String.format(strLivePatternNoShare, oWCLiveMatch.Data.Match.Actions.Action.Kind.code, strTime, oWCLiveMatch.Data.Match.Actions.Action.Kind.text, strTeam, oWCLiveMatch.Data.Match.Actions.Action.Period.text, strShareText, strMatchLink));
                        }
                        
                    }
                    
                }
                else 
                
                    for (var i = 0; i < oWCLiveMatch.Data.Match.Actions.Action.length; i++) {
                        // only show the selected events (goals and start/stop)
                        if (oWCLiveMatch.Data.Match.Actions.Action[i].Kind.code in match_live_events) {
                            var strTime = "";
                            var strPlayer = "";
                            var strTeam = "";
                            oWCLiveMatch.Data.Match.Actions.Action[i].Time.text == undefined ? strTime = "" : strTime = oWCLiveMatch.Data.Match.Actions.Action[i].Time.text;
                            oWCLiveMatch.Data.Match.Actions.Action[i].Player.text == undefined ? strPlayer = "" : strPlayer = oWCLiveMatch.Data.Match.Actions.Action[i].Player.text;
                            oWCLiveMatch.Data.Match.Actions.Action[i].Team.text == undefined ? strTeam = "" : strTeam = oWCLiveMatch.Data.Match.Actions.Action[i].Team.text;
                            var strShareText = "";
                            strShareText = "[#" + oWCLiveMatch.Data.Match.Team[0].ShortName + " " + oWCLiveMatch.Data.Match.Result.Live.H + ":" + oWCLiveMatch.Data.Match.Result.Live.A + " #" + oWCLiveMatch.Data.Match.Team[1].ShortName + "] " + strTime + " " + oWCLiveMatch.Data.Match.Actions.Action[i].Kind.text + " " + strPlayer + " (" + oWCLiveMatch.Data.Match.Actions.Action[i].Period.text + ")";
                            strShareText = strShareText.split("'").join("&#039;");
                            strShareText = URLEncode(strShareText);
                            if (oWCLiveMatch.Data.Match.Actions.Action[i].Kind.code in match_live_share_events) {
                                $("#live" + oWCLiveMatch.Data.Match.code).prepend(String.format(strLivePattern, oWCLiveMatch.Data.Match.Actions.Action[i].Kind.code, strTime, oWCLiveMatch.Data.Match.Actions.Action[i].Kind.text, strTeam, oWCLiveMatch.Data.Match.Actions.Action[i].Period.text, strShareText, strMatchLink));
                            }
                            else {
                                $("#live" + oWCLiveMatch.Data.Match.code).prepend(String.format(strLivePatternNoShare, oWCLiveMatch.Data.Match.Actions.Action[i].Kind.code, strTime, oWCLiveMatch.Data.Match.Actions.Action[i].Kind.text, strTeam, oWCLiveMatch.Data.Match.Actions.Action[i].Period.text, strShareText, strMatchLink));
                            }
                        }
                    }
                setTimeout('$("div .match_live > table").fadeIn();', 150);
            }
        }
    }
    xhr.send();
}

function shareFacebook(strUrl, strTitle){
    chrome.tabs.create({
        url: String.format(share_facebook, URLEncode(strUrl), escape(strTitle.replaceLatinChar().split("%23").join("")))
    });
}

function shareBuzz(strUrl, strTitle){
    chrome.tabs.create({
        url: String.format(share_buzz, URLEncode(strUrl), strTitle.replaceLatinChar().split("%26%23039%3B").join("'").split("%23").join(""))
    });
}

function shareTwitter(strUrl, strTitle){
    $.post("http://goo.gl/api/url", {
        user: "toolbar@google.com",
        url: strUrl,
        auth_token: doit(strUrl)
    }, function(data){
        if (data.short_url != undefined) {        
            chrome.tabs.create({
                url: String.format(share_twitter, strTitle.replaceLatinChar().split("%26%23039%3B").join("'") + " " + URLEncode(data.short_url))
            });
        }
    }, "json");
}

function showMatch(strUrl){
    if (strUrl != "") {
        chrome.tabs.create({
            url: (strUrl)
        });
    }
}

//------ controls events
function onChkMatchClick(){
    bRefreshMyTeam = true;
    
    if ($(this).attr("checked")) {
        trackEvent("FollowMatch", $(this).attr("teams"));
        oWCSelectedMatches[$(this).attr("id").split("chk").join("")] = 1
    }
    else {
        oWCSelectedMatches[$(this).attr("id").split("chk").join("")] = undefined;
        
        // uncheck follow_my_group_team if a team of my group is unchecked
        if (localStorage['follow_my_group_teams'] == 1) {
            if ($(this).attr("group") == localStorage['my_team_group_id']) {
                localStorage['follow_my_group_teams'] = 0;
                $("#chk_follow_my_group_teams").attr("checked", false);
            }
        }
        
        // uncheck follow_my_team if my_team is unchecked 
        if (($(this).attr("team_a") == localStorage['my_team'].split("|")[0]) || (($(this).attr("team_b") == localStorage['my_team'].split("|")[0]))) 
            if (localStorage['follow_my_team'] == 1) {
                localStorage['follow_my_team'] = 0;
                $("#chk_follow_my_team").attr("checked", false);
            }
        
        // uncheck follow_all_teams if any match is unchecked
        $("#chk_follow_all_teams").attr("checked", false);
        localStorage['follow_all_teams'] = 0;
    }
    localStorage.setObject("wcSelectedMatches", oWCSelectedMatches);
}

function onSelectAllClick(strId){
    var bFound = false;
    // select all checkboxes
    $("#" + strId + " > div > div > div >div:visible").find('*:checkbox').each(function(){
        bFound = true;
        if (!$(this).attr("checked")) {
            oWCSelectedMatches[$(this).attr("id").split("chk").join("")] = 1;
            $(this).attr("checked", true);
        }
    })
    if (!bFound) {
        $("#" + strId + "> div:visible").find('*:checkbox').each(function(){
            if (!$(this).attr("checked")) {
                oWCSelectedMatches[$(this).attr("id").split("chk").join("")] = 1;
                $(this).attr("checked", true);
            }
        })
    }
    localStorage.setObject("wcSelectedMatches", oWCSelectedMatches);
}

function onSelectNoneClick(strId){
    var bFound = false;
    // deselect all checkboxes
    $("#" + strId + " > div > div > div >div:visible").find('*:checkbox').each(function(){
        bFound = true;
        if ($(this).attr("checked")) {
            oWCSelectedMatches[$(this).attr("id").split("chk").join("")] = undefined;
            $(this).attr("checked", false);
            // uncheck follow_my_group_team if a team of my group is unchecked
            if (localStorage['follow_my_group_teams'] == 1) {
                if ($(this).attr("group") == localStorage['my_team_group_id']) {
                    localStorage['follow_my_group_teams'] = 0;
                    $("#chk_follow_my_group_teams").attr("checked", false);
                }
            }
            
            // uncheck follow_my_team if my_team is unchecked 
            if (($(this).attr("team_a") == localStorage['my_team'].split("|")[0]) || (($(this).attr("team_b") == localStorage['my_team'].split("|")[0]))) 
                if (localStorage['follow_my_team'] == 1) {
                    localStorage['follow_my_team'] = 0;
                    $("#chk_follow_my_team").attr("checked", false);
                }
        }
    })
    
    if (!bFound) {
        $("#" + strId + "> div:visible").find('*:checkbox').each(function(){
            if ($(this).attr("checked")) {
                oWCSelectedMatches[$(this).attr("id").split("chk").join("")] = undefined;
                $(this).attr("checked", false);
                // uncheck follow_my_group_team if a team of my group is unchecked
                if (localStorage['follow_my_group_teams'] == 1) {
                    if ($(this).attr("group") == localStorage['my_team_group_id']) {
                        localStorage['follow_my_group_teams'] = 0;
                        $("#chk_follow_my_group_teams").attr("checked", false);
                    }
                }
                
                // uncheck follow_my_team if my_team is unchecked 
                if (($(this).attr("team_a") == localStorage['my_team'].split("|")[0]) || (($(this).attr("team_b") == localStorage['my_team'].split("|")[0]))) 
                    if (localStorage['follow_my_team'] == 1) {
                        localStorage['follow_my_team'] = 0;
                        $("#chk_follow_my_team").attr("checked", false);
                    }
            }
        })
    }
    
    localStorage.setObject("wcSelectedMatches", oWCSelectedMatches);
}


function onCmbStageNavigationChange(){
    var currentStage = $("#cmb_popup_stage_navigation").val();
    $(".stage:lt(" + currentStage + ")").hide();
    $(".stage:gt(" + currentStage + ")").hide();
    $(".stage:eq(" + currentStage + ")").show();
}



function selectTabs(strIdTab, strIdGroup){
    $(strIdTab).tabs("select", strIdGroup);
}

function scrollGo(){
    var x = $(this).offset().top - 100; // 100 provides buffer in viewport
    $('div').animate({
        scrollTop: x
    }, 500);
}

function onMyTeamClick(){
    var strUrl = getUI("main_url");
    if (!(localStorage['my_team'].split("|")[2] == '---')) 
        strUrl += String.format(url_team, localStorage['my_team'].split("|")[0]);
    if (strUrl != "") 
        chrome.tabs.create({
            url: strUrl
        });
    
}

function onLoadMoreNewsClick(){
    currentNew++;
    if (currentNew >= oWCTeamNews.channel.item.length) {
        $("#popup_txt_load_more_news").hide();
    }
    else {
    
        $("#" + getID(oWCTeamNews.channel.item[currentNew].link)).slideToggle('slow', function(){
        });
        
        var divOffset = $('#div_popup_latest_news').offset().top;
        var pOffset = $('#div_popup_latest_news div:eq(' + currentNew + ')').offset().top;
        var pScroll = pOffset - divOffset;
        $('#div_popup_latest_news').animate({
            scrollTop: '+=' + pScroll + 'px'
        }, 1000, '');
    }
}

function getID(strUrl){
    var myregexp = /[0-9]+/;
    var match = myregexp.exec(strUrl);
    if (match != null) {
        result = match[0];
    }
    else {
        result = "";
    }
    return result;
}


function getTeamConfig(){
    var strTeamUrl = "";
    
    strTeamUrl = getUI('main_url_feed_2') + feed_teams;
    
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            var json = "";
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            
            json = $.xml2json(xmlString);
            
            
            if (json != "") {
                oWCTeams = new Array(json.Data.Team.length);
                oWCTeamsSorted = new Array();
                for (var i = 0; i < json.Data.Team.length; i++) {
                    oWCTeams[json.Data.Team[i].ShortName] = json.Data.Team[i];
                    oWCTeamsSorted.push(json.Data.Team[i].ShortName);
                }
                localStorage.setObject('wcTeams', oWCTeams);
                localStorage.setObject('wcTeamsSorted', oWCTeamsSorted);
                loadMyTeamCombo();
            }
        }
    }
    xhr.send();
}

function loadMyTeamCombo(){
    var options = '';
    options += '<option value="---|---|---">' + getUI("config_txt_all_teams") + '</option>';
    for (var i = 0; i < oWCTeamsSorted.length; i++) {
        options += '<option value="' + oWCTeams[oWCTeamsSorted[i]].code + '|' + oWCTeams[oWCTeamsSorted[i]].ShortName + '|' + oWCTeams[oWCTeamsSorted[i]].FullName + '">' + oWCTeams[oWCTeamsSorted[i]].FullName + '</option>';
    }
    $("#cmb_my_team").html(options);
    var my_team = localStorage['my_team'];
    if (!my_team || my_team == '---|---|---') {
        localStorage.setItem('my_team', $("#cmb_my_team").val());
        localStorage.setObject('follow_my_team', 0);
        localStorage.setObject('follow_my_group_teams', 0);
        
        $("#div_follow_my_team :input").attr("disabled", true);
        $("#div_follow_my_team :input").removeAttr("checked");
        $("#div_follow_my_team :span").attr("disabled", true);
        $("#div_follow_my_team :span").attr("class", "disabled");
        
        
        $("#div_follow_my_group_teams :input").attr("disabled", true);
        $("#div_follow_my_group_teams :input").removeAttr("checked");
        $("#div_follow_my_group_teams :span").attr("disabled", true);
        $("#div_follow_my_group_teams :span").attr("class", "disabled");
        
        $("#team_flag").hide();
    }
    else {
        $("#cmb_my_team").find("option").each(function(){
            if ($(this).val().split("|")[0] == my_team.split("|")[0]) {
                $(this).attr("selected", true);
            }
        });
        
        
        $("#div_follow_my_team :span").removeAttr("disabled");
        $("#div_follow_my_team :span").removeAttr("class");
        $("#div_follow_my_team :input").removeAttr("disabled");
        
        $("#div_follow_my_group_teams :span").removeAttr("disabled");
        $("#div_follow_my_group_teams :span").removeAttr("class");
        $("#div_follow_my_group_teams :input").removeAttr("disabled");
        
        $("#team_flag").attr("src", String.format(flag_pattern_m, $("#cmb_my_team").val().split("|")[1]));
        $("#team_flag").show();
        
    }
}

function onMyTeamChanged(){
    trackEvent("MyTeam", $("#cmb_my_team").val().split("|")[1]);
    
    bRefreshMyTeam = true;
    bMatchesLoaded = false;
    
    if ($("#cmb_my_team").val() == '---|---|---') {
        $("#div_follow_my_team :input").attr("disabled", true);
        $("#div_follow_my_team :input").removeAttr("checked");
        $("#div_follow_my_team :span").attr("disabled", true);
        $("#div_follow_my_team :span").attr("class", "disabled");
        
        $("#div_follow_my_group_teams :input").attr("disabled", true);
        $("#div_follow_my_group_teams :input").removeAttr("checked");
        $("#div_follow_my_group_teams :span").attr("disabled", true);
        $("#div_follow_my_group_teams :span").attr("class", "disabled");
        
        $("#team_flag_config").hide();
        
        localStorage.setObject('follow_my_team', 0);
        localStorage.setObject('follow_my_group_teams', 0);
        
    }
    else {
        if (localStorage['my_team'] == '---|---|---') {
            localStorage.setObject('follow_my_team', 1);
            localStorage.setObject('follow_my_group_teams', 1);
            $("#chk_follow_my_team").attr("checked", true);
            $("#chk_follow_my_group_teams").attr("checked", true);
        }
        $("#div_follow_my_team :span").removeAttr("disabled");
        $("#div_follow_my_team :span").removeAttr("class");
        $("#div_follow_my_team :input").removeAttr("disabled");
        
        $("#div_follow_my_group_teams :span").removeAttr("disabled");
        $("#div_follow_my_group_teams :span").removeAttr("class");
        $("#div_follow_my_group_teams :input").removeAttr("disabled");
        
        
        $("#team_flag_config").attr("src", String.format(flag_pattern_s, $("#cmb_my_team").val().split("|")[1]));
        $("#team_flag_config").show();
    }
    localStorage.setItem('my_team', $("#cmb_my_team").val());
    
    chrome.extension.sendRequest({
        getResults: "refreshMatches"
    }, function(response){
        oWCSelectedMatches = JSON.parse(response.selectedMatches);
    });
    
    refreshExtensionIcon();
}

function onChkFollowMyTeamChanged(){
    bMatchesLoaded = false;
    if ($('#chk_follow_my_team').is(':checked')) {
        localStorage.setObject('follow_my_team', 1);
    }
    else 
        localStorage.setObject('follow_my_team', 0);
    chrome.extension.sendRequest({
        getResults: "refreshMatches"
    }, function(response){
        oWCSelectedMatches = JSON.parse(response.selectedMatches);
        
    });
    
    
}

function onChkFollowMyGroupTeamsChanged(){
    bMatchesLoaded = false;
    if ($('#chk_follow_my_group_teams').is(':checked')) {
        localStorage.setObject('follow_my_group_teams', 1);
    }
    else 
        localStorage.setObject('follow_my_group_teams', 0);
    
    chrome.extension.sendRequest({
        getResults: "refreshMatches"
    }, function(response){
        oWCSelectedMatches = JSON.parse(response.selectedMatches);
        
    });
}

function onChkFollowAllTeamsChanged(){
    bMatchesLoaded = false;
    if ($('#chk_follow_all_teams').is(':checked')) 
        localStorage.setObject('follow_all_teams', 1);
    else 
        localStorage.setObject('follow_all_teams', 0);
    
    chrome.extension.sendRequest({
        getResults: "refreshMatches"
    }, function(response){
        oWCSelectedMatches = JSON.parse(response.selectedMatches);
        
    });
}


function getGroupShortName(strName){
    var strTemp = strName;
    strTemp = strTemp.split("مجموعة ").join("");
    strTemp = strTemp.split("Grupo ").join("");
    strTemp = strTemp.split("Gruppe ").join("");
    strTemp = strTemp.split("Group ").join("");
    return strTemp;
}
